package com.jingjiu.homeservicesbiz.service;

import com.jingjiu.homeservicesapi.Vo.LoginVo;
import com.jingjiu.homeservicesapi.domain.UserInfo;
import com.jingjiu.homeservicesapi.domain.UserRelative;
import com.jingjiu.homeservicesapi.dto.UserDTO;
import com.jingjiu.homeservicesapi.dto.UserRelativeDTO;
import com.jingjiu.homeservicesapi.enums.ResultEnum;
import com.jingjiu.homeservicesbiz.Jwt.JwtUtil;
import com.jingjiu.homeservicesbiz.exception.OlinkBaseException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserLoginServer {
    @Autowired
    private UserInfoServiceImpl userInfoService;
   @Autowired
   private UserRelativeServiceImpl userRelativeService;

    public LoginVo userLogin(String account, String password) {
        // 1.根据账号查询用户信息
        UserInfo userInfo = userInfoService.selectUserInfoByAccount(account);
        if (userInfo == null) {
            throw new OlinkBaseException(ResultEnum.USER_INFO_NOT_EXIST);
        }

        // 2.验证密码
        if (!userInfo.getPassword().equals(password)) {
            throw new OlinkBaseException(ResultEnum.USER_PASSWORD_NOT_RIGHT);
        }
        userInfo.setLastLoginTime(new Date(System.currentTimeMillis()));
        String token = JwtUtil.createToken(userInfo.getId(), userInfo.getAccount());
        return new LoginVo(token, userInfo.getId());
    }

    public String userRegister(UserDTO userDTO) {
        // 1.检查账号是否已存在
        UserInfo existingUser = userInfoService.selectUserInfoByAccount(userDTO.getAccount());
        if (existingUser != null) {
            return "账号已存在"; // 账号已存在
        }
        // 2. 保存用户主信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUserType("0");  //默认普通用户
        BeanUtils.copyProperties(userDTO, userInfo);
        userInfoService.insertUserInfo(userInfo);

        // 3. 保存亲属信息
        if (userDTO.getUserRelativeDTOs() != null) {
            for (UserRelativeDTO relativeDTO : userDTO.getUserRelativeDTOs()) {
                UserRelative relative = new UserRelative();
                BeanUtils.copyProperties(relativeDTO, relative);
                relative.setUserId(userInfo.getId()); // 外键绑定
                userRelativeService.insertUserRelative(relative);
            }
        }

        return "success";
    }

}